﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Castle.ActiveRecord;
using Castle.ActiveRecord.Framework.Config;
using CosyTrade.Core;
using CosyTrade.Data;

namespace CosyTrade.InternalServer
{
    class Program
    {
        static void Main(string[] args)
        {
            AddinServices services = AddinServices.Instance;
            services.InitalizeAddin();
            InitOrm();
            services.StartAddin();
            
            do
            {
                IList<IAddin> runningAddin = services.AddinManager.GetAddinList();
                Console.WriteLine("RunnigAddin:");
                foreach (IAddin addin in runningAddin)
                    Console.WriteLine("$:" + addin.AddinName);
                Console.Write("Server is Running, Press 'exit' to Exit.\r\n>");
            } while (Console.ReadLine() != "exit");

            services.Stop();
        }

        private static void InitOrm()
        {
            string defaultDbConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "dbConfig.xml");
            XmlConfigurationSource source = new XmlConfigurationSource(defaultDbConfigPath);
            Type[] ormTypes = GetOrmTypes();
            OrmDataAccess.Initialize(source, ormTypes);
        }

        private static Type[] GetOrmTypes()
        {
            Assembly contractAssembly =
                Assembly.LoadFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CosyTrade.Contract.dll"));
            Type[] assemblyTypes = contractAssembly.GetTypes();
            List<Type> ormTypes = new List<Type>();
            foreach (Type assemblyType in assemblyTypes)
            {
                if (!assemblyType.IsDefined(typeof(ActiveRecordAttribute), false)) continue;
                if (!assemblyType.IsDefined(typeof(SerializableAttribute), false))
                    throw new Exception(string.Format("{0} Not Mark SerializableAttribute", assemblyType.FullName));
                ormTypes.Add(Type.GetType(assemblyType.AssemblyQualifiedName));
            }
            return ormTypes.ToArray();
        }
    }
}
